package gui.toolbar;

import gui.MainWindow;
import gui.view.standard.ViewTriggers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JToolBar;

import model.MetroModel;
import model.ModelChangeListener;
import model.objects.EdiLine;

import com.nightpiter.model.objects.Line;

public class LineToolBar extends JToolBar {
	
	public LineToolBar(MainWindow parent) {
		LineBox lineBox = new LineBox(); 
		add(lineBox);
		add(new EditLineButton(parent, lineBox));
		add(new AddLineButton(parent));		
	}
	class LineBox extends JComboBox implements ModelChangeListener{
		LineBox() {			
			MetroModel.getInstance().addModelChangeListener(this);			
			setFocusable(false);
			addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					ViewTriggers.addTunelsLine = (Line) LineBox.this.getSelectedItem();
				}
				
			});

			
		}

		@Override
		public void modelChanged(boolean newObjectsAdded) {
			Line selected = (Line) this.getSelectedItem();
			
			this.removeAllItems();
			for(EdiLine line:MetroModel.getInstance().getLines()) {
				this.addItem(line);
			}
			if(MetroModel.getInstance().getLines().contains(selected)) {
				this.setSelectedItem(selected);
			}
			
		}
	}
	
	class EditLineButton extends JButton {
		EditLineButton(final MainWindow parent, final LineBox box){
			super("Edit line");
			addActionListener(new ActionListener() {				
				@Override
				public void actionPerformed(ActionEvent e) {
					parent.getMainPanel().getProperties().editLine((EdiLine) box.getSelectedItem());
				}
				
			});
			
		}
	}
	
	class AddLineButton extends JButton {
		AddLineButton(final MainWindow parent){
			super("Add line");
			addActionListener(new ActionListener() {				
				@Override
				public void actionPerformed(ActionEvent e) {
					EdiLine line = new EdiLine("", 0, 0);
					MetroModel.getInstance().addLine(line);
					parent.getMainPanel().getProperties().editLine(line);
				}
				
			});
			
		}
	}

}
